import TransferTools.Filer as ts
from pathlib import Path
import json
import os

def send_file(path: Path, front_controller):
    # 创建一个通信连接
    communicator = ts.create_server()
    print('正在建立通信')
    conn, addr = communicator.accept() # 等待连接

    file_info = handle_file_info(path)  # 在这个里面已经切分过文件了
    info_dict = json.loads(file_info)
    # 交换信息
    protocol_send(conn, file_info)

    send_folder = Path(info_dict.get("sendFolderTemp"))

    file_count = info_dict.get('fileCount')
    print(f"总文件数为：{info_dict.get('fileCount')}")
    try:
        # 文件传输
        for index, path in enumerate(send_folder.iterdir()):
            ts.send_file_tcp(ts.Settings.host, ts.Settings.port_trans, path)
            current_value = int((index + 1) / file_count * 100)
            # 更新进度条的相关值
            front_controller.status[0] = current_value
            front_controller.processing_view()

        # 接收对方文件接收完毕信号
        protocol_recv(conn, "success")

        # 关闭通信连接
        ts.close_connection(conn)
    finally:
        #删除缓存文件
        folder = Path(info_dict.get('sendFolderTemp'))

        ts.delete_folder(folder)

def receive_file(ip, front_controller):
    # 连接通信端口
    conn = ts.connect_server(ip)
    # 获取文件信息
    file_info_json = protocol_recv(conn)
    file_info = json.loads(file_info_json)

    out_path = Path(f"./temp_{os.getpid()}")

    file_count = file_info.get('fileCount')
    # 创建文件夹
    out_path.mkdir()
    try:
        for i in range(file_info.get("fileCount")):
            ts.receive_file_tcp(ip, ts.Settings.port_trans, out_path)
            value = int(((i + 1) / file_count) * 100)
            front_controller.status[0] = value
            front_controller.processing_view()
        # 合并文件
        ts.merge_files(out_path, file_info.get('fileName'))
        protocol_send(conn, 'success')
    finally:
        # 删除临时文件夹
        ts.delete_folder(out_path)


def handle_file_info(path: Path)->str:
    # 分割文件
    folder = Path(ts.split_file(path, 20))
    file_names = [item for item in folder.iterdir()]
    file_count = len(file_names)
    file_name = path.name # Path对象

    file_info = json.dumps({
        'fileCount': file_count,
        'fileName': file_name,
        'sendFolderTemp': str(folder),
    })

    return file_info

def protocol_send(conn, msg):
    conn.send(msg.encode())
    while True:
        msg2 = conn.recv(4096).decode()
        if msg2 == 'yes':   break

def protocol_recv(conn, msg='')->str:
    msg = conn.recv(1048576).decode()
    conn.send('yes'.encode())
    return msg


def get_local_ip():
    return ts.get_local_ip()